package cn.kongwg.juc;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author kongwg
 * @create 2021-05-03 19:55
 */

class Mytask extends RecursiveTask<Integer> {

    private static final int Number_m = 10;

    private int start;
    private int end;
    private int result;

    public Mytask() {
    }

    public Mytask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if ((end - start) > Number_m) {
            for (int i = start; i <= end; i++) {
                result = result +i;
            }
        }else{
            int mid = (end -start)/2;
            Mytask mytask = new Mytask(start, mid);
            Mytask mytask1 = new Mytask(mid, end);
            mytask.fork();
            mytask1.fork();

            result =  mytask.join() +mytask1.join();


        }
        return result;
    }
}

public class ForkJoinDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Mytask mytask = new Mytask(0, 100);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> submit = forkJoinPool.submit(mytask);
        System.out.println("submit = " + submit.get());
        forkJoinPool.shutdown();
    }
}
